package com.dpj.wait_test;

import lombok.extern.slf4j.Slf4j;


@Slf4j(topic = "c. AlternatePrint2 ")
public class AlternatePrint2 {
    public static void main(String[] args) {
        WaitNotify wn=new WaitNotify(1,3);
        new Thread(()-> {
            try {
                wn.print("a", 1, 2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()->{
            try {
                wn.print("b",2,3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                wn.print("c",3,1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }
}
/*
输出内容  等待标记   下一个标记是什么
a           1       2
b           2       3
c           3       1

 */
class WaitNotify{
    // 打印   a  1  2
    public void print(String str,int waitFlag,int nextFlag) throws InterruptedException {
        for (int i = 0; i <loopNumber ; i++) {
            synchronized (this){
                while (flag!=waitFlag){
                    this.wait();
                }

                System.out.println(str);
                flag=nextFlag;
                this.notifyAll();

            }
        }
    }
    //等待标记
    private  int flag;

    //循环次数
    private int loopNumber;

    public WaitNotify(int flag, int loopNumber) {
        this.flag = flag;
        this.loopNumber = loopNumber;
    }
}
